package com.jty.module_user.viewmodel

import androidx.databinding.ObservableBoolean
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.RegexUtils
import com.jty.lib_base.base.BaseBean
import com.jty.lib_base.base.BaseViewModel
import com.jty.lib_base.base.MyApplication
import com.jty.lib_base.binding.command.BindingAction
import com.jty.lib_base.binding.command.BindingCommand
import com.jty.lib_base.bus.event.SingleLiveEvent
import com.jty.lib_base.data.DataRepository
import com.jty.lib_base.event.LiveBusCenter
import com.jty.lib_base.extension.ApiSubscriptHelper
import com.jty.lib_base.utils.ComUtils
import com.jty.lib_base.utils.RxThreadHelper
import com.orhanobut.logger.Logger
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import okhttp3.RequestBody
import java.util.concurrent.TimeUnit


/**
 * author: zhouyh
 * created on: 2021/9/18 5:35 下午
 * description:主页viewmodel
 */
class ModifyPhoneViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    val loginpwd = model.getLoginPassword()
    var inPwd = MutableLiveData<String>()
    var inPhone = MutableLiveData<String>()
    var inVerification = MutableLiveData<String>()
    val inSecond = MutableLiveData<String>("获取验证码")
    var second = 60
    var outVerification: String? = null

    val eyeState : ObservableBoolean = ObservableBoolean(false)

    override fun onCreate() {
        super.onCreate()
        tvTitle.set("变更手机号")
    }

    val uc = UIChangeEvent()

    /**
     * UI刷新事件 用于观察者
     */
    class UIChangeEvent{
        val ableClickVeri: SingleLiveEvent<Boolean> = SingleLiveEvent()
    }

    val modifyPhone: BindingCommand<Void> = BindingCommand(BindingAction {
        Logger.e("登录密码：${loginpwd}, 输入密码：${inPwd.value}, 输入手机号：${inPhone.value}, 收入验证码：${inVerification.value}")
        modifyPhone()
    })

    val onEyeClickCommand:BindingCommand<Boolean> = BindingCommand(BindingAction {
        if (eyeState.get()){
            eyeState.set(false)
        }else{
            eyeState.set(true)
        }
    })

    val onClickVerification:BindingCommand<Void> = BindingCommand(BindingAction {
        if(!RegexUtils.isMobileSimple(inPhone.value?.trim())) {
            showNormalToast("手机号码格式错误")
            return@BindingAction
        }
        sendModifyPhoneCode()
    })
    private fun sendModifyPhoneCode(){
        val json = ComUtils.getHashmapByStr(
            arrayOf("mobile","type"),
            arrayOf(inPhone.value?.trim().toString(),11)
        )
        var requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))
        model.apply {
            this.getCode(requestBody)
                .compose(RxThreadHelper.rxSchedulerHelper(this@ModifyPhoneViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriptHelper<BaseBean<String>>() {
                    override fun onResult(t: BaseBean<String>) {
                        //Logger.e(t.toString())
                        dismissLoading()
                        if (t.code == 0) {
                            outVerification = t.data
                            updateSecond()
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showNormalToast(msg)
                    }
                })
        }
    }

    private fun updateSecond() {
        uc.ableClickVeri.postValue(false)
        Observable.intervalRange(1, 60, 0, 1, TimeUnit.SECONDS)
            .compose(RxThreadHelper.rxSchedulerHelper(this@ModifyPhoneViewModel))
            .subscribe(object : Observer<Long> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: Long) {
                    second = (60 - t).toInt();
                    inSecond.postValue("${second}s")
                }

                override fun onError(e: Throwable) {
                }

                override fun onComplete() {
                    second = 60
                    inSecond.postValue("发送验证码")
                    uc.ableClickVeri.postValue(true)
                }

            });
    }

    private fun modifyPhone(){
        if (inPwd.value.isNullOrBlank() || inPhone.value.isNullOrBlank()) {
            showNormalToast("手机密码不能为空")
            return
        }

        if (inVerification.value.isNullOrBlank()){
            showNormalToast("验证码不能为空")
            return
        }
        if(inPwd.value?.trim() != loginpwd) {
            showNormalToast("密码错误")
            return
        }
        if(!RegexUtils.isMobileSimple(inPhone.value?.trim())) {
            showNormalToast("手机号码格式错误")
            return
        }
        if(!outVerification.equals(inVerification.value?.trim())) {
            showNormalToast("验证码错误")
            return
        }

        val json = ComUtils.getHashmapByStr(
            arrayOf( "mobile", "password", "verCode"),
            arrayOf( inPhone.value.toString().trim(),inPwd.value.toString().trim(), inVerification.value.toString().trim())
        )
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))

        model.apply {
            this.modifyPhone(requestBody)
                .compose(RxThreadHelper.rxSchedulerHelper(this@ModifyPhoneViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriptHelper<BaseBean<Any?>>() {
                    override fun onResult(t: BaseBean<Any?>) {
                        //Logger.e(t.toString())
                        dismissLoading()
                        if (t.code == 0) {
                            showNormalToast("修改成功")
                            var userInfoBaean = model.getUserInfoData()
                            userInfoBaean?.mobile = inPhone.value.toString().trim()
                            saveUserInfoData(userInfoBaean!!)
                            LiveBusCenter.posModifyPhoneSuccessEvent(inPhone.value.toString().trim())
                            finish()
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showNormalToast(msg)
                    }
                })
        }

    }






}